package com.caifu.util;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
@PropertySource(value = {"classpath:definition.properties"},encoding = "utf-8")
public class ImageFileUpload {

    // 图片默认缩放比率
    private static final double DEFAULT_SCALE = 0.5d;

    // 缩略图后缀
    private static final String SUFFIX = "-thumbnail";

    @Value("${file.upload.path}")
    private String fileUploadPath;
    @Value("${file.upload.result.path}")
    private String fileUploadResultPath;

    private static String uploadPath;
    private static String uploadResultPath;

    /**
    * 
    * 功能描述：图片上传并压缩
    * 
    * @Param uploadLogoFile 要上传的文件  imagePath 图片文件夹 fileName文件名称 type 文件类型 size文件大小
    * @Return      
    * @Exception   
    * @Author  GZ
    * @Date   2020/8/10 10:13
    */
    public static String imgFileUpload(MultipartFile uploadLogoFile, String imagePath, int size){
        String pathInfo = PathFormat.parse(uploadPath+"/"+imagePath+"/");
        String fileName = Util.currentDateTime()+Util.getRandom(4);
        String type = "png";
        //返回路径
        String returnPath = PathFormat.parse(uploadResultPath)+"/"+imagePath+"/"+fileName+"."+type+"";
        try {
            /**
             * 项目根目录上传
             */
            //WEB端
            File file= new File(pathInfo);
            if(!file.exists()){
                file.mkdirs();
            }
            String targetFilePath = pathInfo+fileName+"."+type;
            long imageSize = uploadLogoFile.getSize();
            String imageBathPath = pathInfo+"/"+fileName+"."+type;
            if(imageSize>1024*500){
                Thumbnails.of(uploadLogoFile.getInputStream()).scale(0.8).toFile(targetFilePath);
                compressPicForScale(imageBathPath,imageBathPath,size,DEFAULT_SCALE);
            }else {
                Thumbnails.of(uploadLogoFile.getInputStream()).scale(1).toFile(targetFilePath);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return returnPath;
    }


    /**
     *
     * @param srcPath 原图片地址
     * @param desPath 目标图片地址
     * @param desFileSize 指定图片大小,单位kb
     * @param accuracy 精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static String compressPicForScale(String srcPath,String desPath,
                                              long desFileSize , double accuracy){
        try {
            File srcFile = new File(srcPath);
            long srcFilesize = srcFile.length();
            System.out.println("原图片:"+srcPath + ",大小:" + srcFilesize/1024 + "kb");
            //递归压缩,直到目标文件大小小于desFileSize
            compressPicCycle(desPath, desFileSize, accuracy);
            File desFile = new File(desPath);
            System.out.println("目标图片:" + desPath + ",大小" + desFile.length()/1024 + "kb");
            System.out.println("图片压缩完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return desPath;
    }

    public static void compressPicCycle(String desPath , long desFileSize,
                                         double accuracy) throws IOException{
        File imgFile = new File(desPath);
        long fileSize = imgFile.length();
        //判断大小,如果小于500k,不压缩,如果大于等于500k,压缩
        if(fileSize <= desFileSize*1024){
            return;
        }
        //计算宽高
        BufferedImage bim = ImageIO.read(imgFile);
        int imgWidth = bim.getWidth();
        int imgHeight = bim.getHeight();
        int desWidth = new BigDecimal(imgWidth).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(imgHeight).multiply(
                new BigDecimal(accuracy)).intValue();
        Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
        //如果不满足要求,递归直至满足小于1M的要求
        compressPicCycle(desPath, desFileSize, accuracy);
    }

    /**
     * 生成缩略图到指定的目录
     *
     * @param path  目录
     * @param files 要生成缩略图的文件列表
     * @throws IOException
     */
    public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException {
        return generateThumbnail2Directory(DEFAULT_SCALE, path, files);
    }

    /**
     * 生成缩略图到指定的目录
     *
     * @param scale    图片缩放率
     * @param pathname 缩略图保存目录
     * @param files    要生成缩略图的文件列表
     * @throws IOException
     */
    public static List<String> generateThumbnail2Directory(double scale, String pathname, String... files) throws IOException {
        Thumbnails.of(files)
                // 图片缩放率，不能和size()一起使用
                .scale(scale)
                // 缩略图保存目录,该目录需存在，否则报错
                .toFiles(new File(pathname), Rename.SUFFIX_HYPHEN_THUMBNAIL);
        List<String> list = new ArrayList<>(files.length);
        for (String file : files) {
            list.add(appendSuffix(file, SUFFIX));
        }
        return list;
    }

    /**
     * 将指定目录下所有图片生成缩略图
     *
     * @param pathname 文件目录
     */
    public static void generateDirectoryThumbnail(String pathname) throws IOException {
        generateDirectoryThumbnail(pathname, DEFAULT_SCALE);
    }

    /**
     * 将指定目录下所有图片生成缩略图
     *
     * @param pathname 文件目录
     */
    public static void generateDirectoryThumbnail(String pathname, double scale) throws IOException {
        File[] files = new File(pathname).listFiles();
        compressRecurse(files, pathname);
    }

    /**
     * 文件追加后缀
     *
     * @param fileName 原文件名
     * @param suffix   文件后缀
     * @return
     */
    public static String appendSuffix(String fileName, String suffix) {
        String newFileName = "";

        int indexOfDot = fileName.lastIndexOf('.');

        if (indexOfDot != -1) {
            newFileName = fileName.substring(0, indexOfDot);
            newFileName += suffix;
            newFileName += fileName.substring(indexOfDot);
        } else {
            newFileName = fileName + suffix;
        }

        return newFileName;
    }


    private static void compressRecurse(File[] files, String pathname) throws IOException {
        for (File file : files) {
            // 目录
            if (file.isDirectory()) {
                File[] subFiles = file.listFiles();
                compressRecurse(subFiles, pathname + File.separator + file.getName());
            } else {
                // 文件包含压缩文件后缀或非图片格式，则不再压缩
                String extension = getFileExtention(file.getName());
                if (!file.getName().contains(SUFFIX) && isImage(extension)) {
                    generateThumbnail2Directory(pathname, file.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 根据文件扩展名判断文件是否图片格式
     *
     * @param extension 文件扩展名
     * @return
     */
    public static boolean isImage(String extension) {
        String[] imageExtension = new String[]{"jpeg", "jpg", "gif", "bmp", "png"};

        for (String e : imageExtension) if (extension.toLowerCase().equals(e)) return true;

        return false;
    }

    public static String getFileExtention(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
        return extension;
    }

    @PostConstruct
    private void init(){
        uploadPath = fileUploadPath;
        uploadResultPath = fileUploadResultPath;
    }

}
